<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>复习函数节流，函数防抖，柯里化，数组转树，jsonp</title>
  </head>
  <body>
    <button>函数节流</button>
    <button id="toTree">数组转树</button>
    <button id="curry">柯里化函数</button>
    函数防抖：<input type="text" />
    <script>
      const areaArr = [
        // 广东省（省级）
        { id: 44, name: '广东省', parentId: 0 },
        // 广东省下辖地级市（二级）
        { id: 4401, name: '广州市', parentId: 44 },
        { id: 4402, name: '韶关市', parentId: 44 },
        { id: 4403, name: '深圳市', parentId: 44 },
        { id: 4404, name: '珠海市', parentId: 44 },
        { id: 4405, name: '汕头市', parentId: 44 },
        { id: 4406, name: '佛山市', parentId: 44 },
        { id: 4407, name: '江门市', parentId: 44 },
        { id: 4408, name: '湛江市', parentId: 44 },
        { id: 4409, name: '茂名市', parentId: 44 },
        { id: 4410, name: '肇庆市', parentId: 44 },
        { id: 4411, name: '惠州市', parentId: 44 },
        { id: 4412, name: '梅州市', parentId: 44 },
        { id: 4413, name: '汕尾市', parentId: 44 },
        { id: 4414, name: '河源市', parentId: 44 },
        { id: 4415, name: '阳江市', parentId: 44 },
        { id: 4416, name: '清远市', parentId: 44 },
        { id: 4417, name: '东莞市', parentId: 44 },
        { id: 4418, name: '中山市', parentId: 44 },
        { id: 4419, name: '潮州市', parentId: 44 },
        { id: 4420, name: '揭阳市', parentId: 44 },
        { id: 4421, name: '云浮市', parentId: 44 },

        // 广州市下辖区县（三级）
        { id: 440101, name: '荔湾区', parentId: 4401 },
        { id: 440102, name: '越秀区', parentId: 4401 },
        { id: 440103, name: '海珠区', parentId: 4401 },
        { id: 440104, name: '天河区', parentId: 4401 },
        { id: 440105, name: '白云区', parentId: 4401 },
        { id: 440106, name: '黄埔区', parentId: 4401 },
        { id: 440107, name: '番禺区', parentId: 4401 },
        { id: 440108, name: '花都区', parentId: 4401 },
        { id: 440109, name: '南沙区', parentId: 4401 },
        { id: 440110, name: '增城区', parentId: 4401 },
        { id: 440111, name: '从化区', parentId: 4401 },
      ];

      function add(a, b, c, d) {
        return a * b * c * d;
      }
      // 节流
      function throttle(fn, wait = 500) {
        let lastTime = 0;
        return function (...args) {
          const now = +new Date();
          if (now - lastTime > wait) {
            lastTime = now;
            fn.apply(this, args);
          }
        };
      }
      // 防抖
      function debounce(fn, wait = 500) {
        let timer = null;
        return function (...args) {
          if (timer) clearTimeout(timer);
          timer = setTimeout(() => {
            fn.call(this, ...args);
          }, wait);
        };
      }
      // 获取学生
      function getStudent(data) {
        console.log('data', data);
      }
      // 创建jsonp
      function createJsonp() {
        const script = document.createElement('script');
        script.src = 'http://localhost:3000/student?callback=getStudent';
        script.onload = () => {
          script.remove();
        };
        document.body.appendChild(script);
      }
      function arrayToTree(data, parentId, parentKey = 'parentId') {
        return data
          .filter((item) => item.parentId === parentId)
          .map((item) => {
            return {
              ...item,
              children: arrayToTree(data, item.id, parentKey),
            };
          });
      }
      // new Map转成树
      function arrayToTreeMap(data) {
        // WeakMap 所有键必须是对象
        // const treeMap = new WeakMap();
        const treeMap = new Map();
        let root = [];
        data.forEach((item) => {
          treeMap.set(item.id, {
            ...item,
            children: [],
          });
          const currentNode = treeMap.get(item.id);
          const parentNode = treeMap.get(item.parentId);
          if (parentNode) {
            parentNode.children.push(currentNode);
          } else {
            root.push(currentNode);
          }
        });
        return root;
      }
      // 柯里化函数
      /* function curryFn(fun, ...args) {
        let allArgs = [];
        return function (...restArgs) {
          allArgs = [...args, ...restArgs];
          if (allArgs.length >= fun.length) {
            return fun.apply(this, allArgs);
          } else {
            return curryFn(fun, ...allArgs);
          }
        };
      } */
      function curryFn(fun, ...args) {
        let allArgs = [];
        function inner(...restArgs) {
          allArgs = [...allArgs, ...restArgs];
          if (allArgs.length >= fun.length) {
            return fun.apply(this, allArgs);
          } else {
            return inner;
          }
        }
        return inner;
      }
      const btn = document.querySelector('button');
      const inp = document.querySelector('input');
      const toTree = document.querySelector('#toTree');
      const curry = document.querySelector('#curry');
      btn.addEventListener('click', throttle(createJsonp, 800));
      inp.addEventListener(
        'input',
        debounce((ev) => {
          console.log(ev.target.value);
        }, 1000)
      );
      toTree.addEventListener('click', function () {
        // const result = arrayToTree(areaArr, 0, 'parentId');
        const result = arrayToTreeMap(areaArr);
        console.log('result', result);
      });
      curry.addEventListener('click', function () {
        const func = curryFn(add)(1, 2);
        const result = func(3);
        const res = result(4);
        console.log('result', res);
      });
    </script>
  </body>
</html>
